<template>
  <div :style="{ paddingTop: paddingTop + 'px' }" class="page_wrap">
    <!-- 导航组件 开始 -->
    <navbar :isShowPre="true" :isShowHome="true" :isShowTxtTitle="true" navTitle="选择售点名称"></navbar>
    <!-- 导航组件 结束 -->

    <!-- 内容 开始-->
    <view class="main_content" :style="{ height: styleMainH + 'px' }">
      <uniSearchBar @input="queryCustomer"></uniSearchBar>

      <div class="div_content">
      <scroll-view @scrolltolower="getCustomerList" scroll-y style="height: 1200rpx">
        <template v-for="item in dataList">
          <div @click="onSelectedPosi(item)" class="list_item flex flex-row" :class="item.isActive ? 'isActive' : ''" :key="item">
            <!-- 位置信息 开始-->
            <div @tap.stop="updateImg(item)">
              <image style="width: 160rpx;height: 160rpx" :src="getimg(item)" />
            </div>
            <div class="place_info">
              <div>
                <!-- 客户名称 -->
                <div>
                  <span class="bold" style="font-family: 微软雅黑">{{ item.name }}</span>
                </div>
                <!-- 客户编码 -->
                <div class="ash">
                  <span>{{ item.code }}</span>
                </div>
              </div>
              <!-- 客户地址  -->
              <div class="ash">{{ item.address }}</div>
              <div style="color: red"  v-if="appletExtraDict.appletCustomerIsAllowShowDebtAmount === '1'">
                欠款金额:{{ item.debtAmount }}
              </div>
            </div>
            <!-- 位置信息 结束-->

            <!-- 操作信息 开始 -->
            <div class="op_wrap">
              <button @tap.stop="updateCu(item)" v-if="appletExtraDict.appletIsAllowModifyCustomer === '1'" type="primary" class="cancel_btn btn_margin btn_base update_btn btn_op" size="mini">修改</button>
<!--              <button @tap.stop="credit(item)"  v-if="appletExtraDict.appletIsAllowModifyCustomer === '1'" type="primary" class="cancel_btn btn_margin btn_base update_btn btn_op" size="mini">授信</button>-->
              <button @tap.stop="updateCu(item)" v-else type="primary" class="primary_btn btn_op btn_base detail_btn" size="mini">查看</button>
<!--              <button @tap.stop="onDetail(item)" type="primary" class="primary_btn btn_op btn_base detail_btn" size="mini">查看二批</button>-->
            </div>
            <!-- 操作信息 结束 -->
          </div>
        </template>
        <end-temp v-if="end"></end-temp>
      </scroll-view>
      </div>
    </view>
    <view>
<!--      新增客户    -->
      <uni-popup ref="popup" type="bottom">
        <div v-if="isCredit">
          <view class="customer" v-if="mask" style="height: 1000rpx;width: 750rpx;background-color: #ffffff">
          <scroll-view :scroll-top="scrollTop" style="height: 850rpx" scroll-y="true" class="scroll-Y">
          <view class="title flex a-item j-content">信用信息</view>
          <view class="line-division"></view>
          <view class="customerContent flex flex-row" >
            <view class="b1">
              <view class="cuInputBox flex flex-row a-item"><view class="label">售点名称</view>
                <view class="cuIpt">
                  {{ creditData.customerName }}
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item">
                <view class="label">售点编码</view>
                <view class="cuIpt">
                  {{ creditData.customerCode }}
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item"><view class="red">*</view><view class="label">地址</view>
                <view class="cuIpt flex flex-row">
                  <input v-model="creditData.deliveryAddress" style="width: 500rpx"  placeholder="请输入客户地址" />
                  <view class="flex a-item j-content col-2" @click="getCreditaddress">
                    <image class="locationImage1" src="https://www.zjjqf.cn/file/static/location.png" ></image>
                  </view>
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item"><view class="red">*</view><view class="label">联系人</view>
                <view class="cuIpt"><input v-model="creditData.contactName" placeholder="请输入客户联系人" /></view>
              </view>
              <view class="cuInputBox flex flex-row a-item">
                <view class="label">联系电话</view>
                <view class="cuIpt">
                  <input v-model="creditData.contactPhone" placeholder="请输入联系人联系电话" />
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item">
                <view class="label">身份证号</view>
                <view class="cuIpt">
                  <input v-model="creditData.cardNo" placeholder="身份证号" />
                </view>
              </view>
            <view class="cuInputBox flex flex-row a-item">
              <view class="label">信用额度</view>
              <view class="cuIpt">
                <input v-model="creditData.creditLimit" placeholder="信用额度" />
              </view>
            </view>
            <view class="cuInputBox flex flex-row a-item">
              <view class="label">信用等级</view>
              <view class="cuIpt">
              <w-select
                  width="500rpx"
                  border="none"
                  :showClose="false"
                  @change="changeCreditlevel"
                  :defaultValue="creditData.creditLevelName || '请选择信用等级'"
                  valueName="label"
                  :list="creditLevelList"
              ></w-select>
              </view>
            </view>
            <view >
              <view class="photoTitle flex a-item">上传客户门店照片</view>
              <view>
                <uni-file-picker
                    fileMediatype="image"
                    :image-styles="imageStyles"
                    :limit="1"
                    @select="select"
                />
              </view>

            </view>
              <view >
                <view class="photoTitle flex a-item">上传客户营业执照</view>
                <view>
                  <uni-file-picker
                      fileMediatype="image"
                      :image-styles="imageStyles"
                      :limit="1"
                      @select="stampSelect"
                  />
                </view>

              </view>
          </view>
          </view>
          </scroll-view>
          <view class="btnBox flex flex-row">
            <button class="cuBtn"  @click="creditSave">保存</button>
          </view>
        </view></div>
        <div v-else><view class="customer" v-if="mask" style="height: 1000rpx;width: 750rpx;background-color: #ffffff">
          <view class="title flex a-item j-content">售点信息</view>
          <view class="line-division"></view>
          <view class="customerContent flex flex-row" :style="{'margin-left': '-'+bWidth+'rpx'}">
            <view class="b1 b1-1">
              <view class="cuInputBox flex flex-row a-item"><view class="red">*</view><view class="label">售点名称</view>
                <view class="cuIpt">
                  <input placeholder="请输入售点名称" :disabled="appletExtraDict.appletIsAllowModifyCustomer !== '1'" v-model="form.name"/>
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item">
                <!-- <view class="red">*</view> -->
                <view class="label">售点编码</view>
                <view class="cuIpt">
                  <view v-if="form.id">{{ form.code }}</view>
                  <input v-else placeholder="售点编码" :disabled="appletExtraDict.appletIsAllowModifyCustomer !== '1'" v-model="form.code" />
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item">
                <view class="label">业务员</view>
                <view class="cuIpt">
                  <picker :disabled="appletExtraDict.appletIsAllowModifyCustomer !== '1'" class="picBox" mode='selector'
                              range-key="name" :range="userList"  @change="changeuser" >
                              <view class="uni-input">{{ form.userName || '请选择业务员' }}</view>
                              </picker>
                  <!-- <w-select
                      width="500rpx"
                      border="none"
                      @change="val=>onchange(val,'userId')"
                      :showClose="false"
                      :disabled="appletExtraDict.appletIsAllowModifyCustomer !== '1'"
                      :defaultValue="form.userName || '请选择业务员'"
                      valueName="name"
                      :list="userList"
                  >
                  </w-select> -->
<!--                  <view v-else>{{ form.userName }}</view>-->
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item"><view class="label">业务员手机</view>
                <view >
                    {{ form.userPhone || '' }}
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item"><view class="red">*</view><view class="label">地址</view>
                <view class="cuIpt flex flex-row">
                  <input :disabled="appletExtraDict.appletIsAllowModifyCustomer !== '1'" v-model="form.address" style="width: 500rpx"  placeholder="请输入客户地址" />
                  <view class="flex a-item j-content col-2" @click="getaddress">
                    <image class="locationImage1" src="https://www.zjjqf.cn/file/static/location.png" ></image>
                  </view>
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item"><view class="red">*</view><view class="label">联系人</view>
                <view class="cuIpt"><input v-model="form.contactName" :disabled="appletExtraDict.appletIsAllowModifyCustomer !== '1'" placeholder="请输入客户联系人" /></view>
              </view>
              <view class="cuInputBox flex flex-row a-item">
                <view class="red">*</view>
                <view class="label">联系电话</view>
                <view class="cuIpt">
                  <input v-model="form.contactPhone" :disabled="appletExtraDict.appletIsAllowModifyCustomer !== '1'" placeholder="请输入联系人联系电话" />
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item">
                <view class="label">二批</view>
                <view class="cuIpt">
                  <view style="width: 500rpx;height:80rpx;overflow: hidden" class="flex a-item"  @tap.stoap="onDetail">
                    {{ form.scustomerName }}
                  </view>
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item">
                <view class="label">拜访线路 </view>
                <view class="cuIpt">
                  <picker  class="picBox" mode='selector'
                              range-key="name" :range="linelist"  @change="changeline" >
                              <view class="uni-input">{{ form.visitLineName?form.visitLineName:'请选择拜访线路' }}</view>
                              </picker>
                <!-- <w-select width="500rpx"
                 border="none"  
                 :list="linelist" 
                 @change="changeline" 
                 valueName="name" 
                 :defaultValue="form.visitLineName || '请选择拜访线路'"
                 :text="name"/> -->
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item">
                <view class="label">拜访时间 </view>
                <view class="cuIpt">
                  <view style="width: 500rpx;height:80rpx;overflow: hidden" class="flex a-item"  @tap.stoap="ontime">
                                  {{ visitTime }}
                              </view>
                <!-- <w-select width="500rpx" border="none" valueName="name"
                :value.sync='form.visitTime' defaultValue="请选择拜访时间"
                ref='visitTimeText' keyName='id'  :list="timelist"  @input="changetime"  multiple/> -->
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item">
                <view class="label">拜访频率 </view>
                <view class="cuIpt">
                  <input placeholder="请输入拜访频率" v-model="form.visitFrequency"/>
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item">
                <view class="red">*</view>
                <view class="label">客户区域</view>
                <view class="cuIpt">
                  <picker class="picBox" mode='selector'
                              range-key="name" :range="areaList"  @change="changearea" >
                              <view class="uni-input">{{ form.customerAreaName || '请选择客户区域' }}</view>
                              </picker>
                    <!-- <w-select
                        width="500rpx"
                        border="none"
                        :showClose="false"
                        @change="changeArea"
                        :defaultValue="form.customerAreaName || '请选择客户区域'"
                        valueName="name"
                        :list="areaList"
                    >
                    </w-select> -->
                  </view>
                </view>
                <view class="cuInputBox flex flex-row a-item">
                <view class="red">*</view>
                <view class="label">客户分类</view>
                <picker class="picBox" mode='selector'
                              range-key="name" :range="customerTypeList"  @change="changecustomerType" >
                              <view class="uni-input">{{ form.customerTypeName || '请选择客户分类' }}</view>
                              </picker>
                <!-- <w-select
                    width="500rpx"
                    border="none"
                    @change="changetype"
                    :showClose="false"
                    :defaultValue="form.customerTypeName || '请选择客户分类'"
                    valueName="name"
                    :list="customerTypeList"
                >
                </w-select> -->
              </view>
            </view>
            <view  class="b1" >
              <view class="cuInputBox flex flex-row a-item">
                <view class="red">*</view>
                <view class="label">部门</view>
                <view class="cuIpt">
                  <picker class="picBox" mode='selector'
                              range-key="name" :range="deptList"  @change="changedept" >
                              <view class="uni-input">{{ form.deptName || '请选择部门' }}</view>
                              </picker>
                  <!-- <w-select
                      width="500rpx"
                      border="none"

                      :showClose="false"
                      @change="val=>onchange(val,'deptId')"
                      :defaultValue="form.deptName || '请选择部门'"
                      valueName="name"
                      :list="deptList"
                  >
                  </w-select> -->
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item"><view class="label">销售体系</view>
                <view class="cuIpt">
                  <picker class="picBox" mode='selector'
                              range-key="name" :range="saleSystemList"  @change="changesaleSystem" >
                              <view class="uni-input">{{form.saleSystemName || '请选择销售体系' }}</view>
                              </picker>
                  <!-- <w-select
                      width="500rpx"
                      border="none"

                      :showClose="false"
                      @change="val=>onchange(val,'saleSystemId')"
                      :defaultValue="form.saleSystemName || '请选择销售体系'"
                      valueName="name"
                      :list="saleSystemList"
                  >
                  </w-select> -->
                </view>
              </view>
              <view class="cuInputBox flex flex-row a-item"><view class="label">结算方式</view>
                <view class="cuIpt">
                  <picker class="picBox" mode='selector'
                              range-key="name" :range="settlementList"  @change="changesettlement" >
                              <view class="uni-input">{{form.settlementName || '请选择结算方式' }}</view>
                              </picker>
                  <!-- <w-select
                      width="500rpx"
                      border="none"
                      :showClose="false"
                      @change="val=>onchange(val,'settlementId')"
                      :defaultValue="form.settlementName || '请选择结算方式'"
                      valueName="name"
                      :list="settlementList"
                  >
                  </w-select> -->
                </view>
              </view>
            </view>
            <view class="b1">
              <view class="fileBox flex flex-column a-item j-content">
                <view>
                  <uni-file-picker
                      fileMediatype="image"
                      :image-styles="imageStyles"
                      :limit="1"
                      @select="select"
                  />
                </view>
                <view class="text flex a-item j-content">上传客户门店照片</view>
                <view class="flex flex-row" @click="getaddress">
                  <image class="locationImage" src="https://www.zjjqf.cn/file/static/location.png" ></image>
                  {{ form.address || '点击获取客户位置' }}
                </view>
              </view>
            </view>
          </view>
          <view class="btnBox flex flex-row">
            <button class="cuBtn" v-if="cuIndex !== 1 && !form.id" @click="reduceCuIndex">上一页</button>
            <button class="cuBtn" v-if="cuIndex !== 3 && !form.id" @click="addCuIndex">下一页</button>
            <button class="cuBtn" v-if="cuIndex === 3 || form.id" @click="save">保存</button>
          </view>
        </view></div>
      </uni-popup>

      <!--遮罩-->
<!--      <view class="mask" @touchmove.stop.prevent="moveHandle"  @click="close" v-if="mask">-->
<!--        <view></view>-->
<!--      </view>-->
    </view>
    <!-- 内容 结束 -->

    <!-- 底部按钮 开始-->
    <div class="footer" v-if="appletExtraDict.appletIsAllowAddCustomer === '1'">
<!--      <button @click="onCancel" type="primary" class="cancel_btn btn_margin" size="mini">取消</button>-->
      <button @click="addCu" type="primary"  class="primary_btn">新增</button>
    </div>
    <!-- 底部按钮 结束-->

  </div>
</template>

<script>
import { uniFilePicker } from '@dcloudio/uni-ui'
import { uniSearchBar } from '@/components/uniSearchBar.vue'
import navmixin from '@/mxins/nav.js'
import { appletBasCustomerArea, appletBasCustomer} from '@/service/api/shopping.js'
import { getToken, setToken, setUserInfo, getUserInfo } from '@/service/auth.js'
import endTemp from "../../components/endTemp";
import {getbasCustomerSellingPointList, basCustomerSellingPointList, getBasSettlementList} from "@/service/api/logistics";
import {getBasCustomerTypeList} from "@/service/api/shopping";
import WSelect from "../../components/w-select/w-select";

import {getBasCustomerAreaList, getSysUserList, getChildSysDeptList, getBasSaleSystemList, appBasCustomerAddOrSave,basLineList} from "@/service/api/logistics";
import {appletExtraDict} from "../../service/api/home";
import {appletBasCustomerCreditAddOrSave, getDict} from "@/service/api/shopping";
import {headerEditCustomer} from "@/service/api/shoprecord";
const form = {
      id: null,
      customerTypeId: null,
      userId: null,
      customerAreaId: null,
      deptId: null,
      saleSystemId: null,
      scustomerName: '',
      userName:'',
      customerTypeName:"",
      address:'',
      visitTime:'',
      visitLineName:''
    }
export default {
  mixins: [navmixin],
  components: {WSelect, uniSearchBar, endTemp, uniFilePicker},
  data() {
    return {
      dataList: [],
      scustomerList:[],
      userInfo: null, //当前用户信息
      creditData:{
      },
      visitTimeText:'',
      query:{
        page:1,
        size:10,
        customerId: '',
        isLast:1
      },
      imageStyles: {
        width: 200,
        height: 200,
      },
      end:false,
      mask: false,
      bWidth: 0,
      cuIndex: 1,
      customerTypeList: [],
      timelist: [
        { id:1,name:'周一'},
        { id:2,name:'周二'},
        { id:3,name:'周三'},
        { id:4,name:'周四'},
        { id:5,name:'周五'},
        { id:6,name:'周六'},
        { id:7,name:'周日'},
        ],
      form:{
        id: null,
        customerTypeId: null,
        userId: null,
        customerAreaId: null,
        deptId: null,
        saleSystemId: null,
        scustomerName: '',
        userName:'',
        customerTypeName:"",
        userPhone: '',
        visitTime: ''
      },
      userList: [],
      areaList: [],
      deptList: [],
      linelist: [],
      saleSystemList: [],
      rules:{
        'name':'客户名称',
        'code':'客户编码',
        'address':'送货地址',
        'contactName': '联系人',
        'customerTypeId': '客户分类',
        'customerAreaId': '客户区域',
        'deptId': '部门',
        },
      positionInfo: {
        address: '',
        longitude: '', //经度
        latitude: '', //纬度
      },
      appletExtraDict:{},
      sourceType: '',
      settlementList: [],
      creditLevelList: [],
      isCredit: false,
      stampFilePath: '',
      type:'',
      visitTime:''

    }
  },
  onLoad(option) {
    // 初始化用户信息、
    this.dataList =[]
    this.Fun_initUserInfo()
    const app = getApp()
    this.sourceType= app.globalData.sourceType
      // 获取客户信息
      appletExtraDict().then(res=>{
          this.appletExtraDict = {}
          res.data.appletExtraDict.forEach(item=>{
              this.appletExtraDict[item.code] = item.value
          })
      })
    const customerId = option.updateId
    if(customerId) {
        this.uniShowLoading()
        headerEditCustomer({customerId}).then(res=>{
            uni.hideLoading()
            if (res.status === 200){
                this.dataList = [res.data]
            }else {
                uni.showToast({title:res.msg})
            }
        }).catch(err=>{
            uni.hideLoading()
            uni.showToast({title:err.msg})
        })
        return
    }

      this.API_appletBasCustomer()

  },
  onShow() {
    const app = getApp()
    try{
      if(app.globalData.scustomerList.length){
        let name = ''
        this.form.scustomerList = app.globalData.scustomerList.map(item=>{
          name += item.name+','
          return {customerId: this.form.id || 0,scustomerId: item.id}}
        )
        this.form.scustomerName = name
      }
    }catch (e) {
      console.log(e)
    }
    try{
            if(app.globalData.timeList.length){
              let name = ''
                this.form.visitTime = app.globalData.timeList.map(item=>{
                  name += item.name+','
                  return  item.id
                }
                )
                this.form.visitTime=JSON.stringify(this.form.visitTime)
                this.visitTime = name
            }
        }catch (e) {
            console.log(e)
        }
  },
  // onReachBottom(){
  //   if (!this.end) {
  //     this.query.page += 1
  //     this.onGet()
  //   }
  // },


  created() {
    getBasCustomerTypeList({size: 999}).then(res=>{
    }).catch(error=>{
      this.customerTypeList = error.content
    })
    getSysUserList({size: 999,businessAttr: 3}).then().catch(err=>{
      this.userList = err.content
    })
    getBasCustomerAreaList().catch(err=>{
      this.areaList = err.content
    })
    basLineList({size: 999}).catch(err=>{
      this.linelist = err.content
    })

    getChildSysDeptList().catch(err=>{
      this.deptList = err.content
    })

    getBasSaleSystemList({size: 999}).catch(err=>{
      this.saleSystemList = err.content
    })

    getBasSettlementList({size: 999}).catch(err=>{
      this.settlementList = err.content
    })
    getDict({dictCode:'t_bas_customer_credit_level',size:999}).catch(
        res=>{this.creditLevelList = res.content}
    )

  },
  methods: {
    ontime(item){
          uni.navigateTo({
              url: `/pages/mine/index/time`,
          })
      },
    changetime(val){
      this.form.visitTime=JSON.stringify(val.map(item=>{return item.id}))
    },
    changeline(val){
      let index=val.detail.value*1
      this.form.visitLineId=this.linelist[index].id
      this.$set(this.form,'visitLineName',this.linelist[index].name)
    },
    changeuser(val){
      let index=val.detail.value>>0
      this.form.userId=this.userList[index].id
      this.$set(this.form,'userName',this.userList[index].name)
      console.log('=============')
      const user = this.userList[~~val.target.value]
      this.$set(this.form,'userPhone',user && user.phone )
    },
    changecustomerType(val){
      let index=val.detail.value*1
      this.form.customerTypeId=this.customerTypeList[index].id
      this.$set(this.form,'customerTypeName',this.customerTypeList[index].name)
    },
    changearea(val){
      let index=val.detail.value*1
      this.form.customerAreaId=this.areaList[index].id
      this.$set(this.form,'customerAreaName',this.areaList[index].name)
    },
    changedept(val){
      let index=val.detail.value*1
      this.form.deptId=this.deptList[index].id
      this.$set(this.form,'deptName',this.deptList[index].name)
    },
    changesaleSystem(val){
      let index=val.detail.value*1
      this.form.saleSystemId=this.saleSystemList[index].id
      this.$set(this.form,'saleSystemName',this.saleSystemList[index].name)
    },
    changesettlement(val){
      let index=val.detail.value*1
      this.form.settlementId=this.settlementList[index].id
      this.$set(this.form,'settlementName',this.settlementList[index].name)
    },
    //初始化查询信息
    init(){
      this.query.page = 1
      this.dataList = []
    },
    // 初始化用户信息
    Fun_initUserInfo() {
      if (getUserInfo()) {
        this.userInfo = JSON.parse(getUserInfo())
      }
    },

    // 接口--获取客户信息
    API_appletBasCustomer() {
      let data = { id: '' }
      this.query.customerIds = this.query.customerId || this.userInfo.customerIds
      // 若业务员登录，不需要传递
      this.uniShowLoading()
      const val = this.query.keyword
      if (this.appletExtraDict.appletIsAllowAllCustomerOrder === '1' || this.query.customerIds){
        getbasCustomerSellingPointList(this.query)
            .then(res => {
              if (this.query.keyword !== val){
                this.uniHideLoading()
                return
              }
              const { content } = res
              if (content.length === 0){
                this.end = true
                this.uniHideLoading()
                return
              }
              this.dataList = [...this.dataList,...content]
              this.uniHideLoading()
              Promise.resolve()
            })
            .catch(err => {
              if (this.query.keyword !== val){
                this.uniHideLoading()
                return
              }
              const { content } = err
              if (content.length === 0){
                this.end = true
                this.uniHideLoading()
                return
              }
              this.dataList = [...this.dataList,...content]
              this.uniHideLoading()
              Promise.resolve()
            })
      }else {
        basCustomerSellingPointList({...this.query,appletUserId: this.userInfo.userId})
            .then(res => {
              if (this.query.keyword !== val){
                this.uniHideLoading()
                return
              }
              const { content } = res
              if (content.length === 0){
                this.end = true
                this.uniHideLoading()
                return
              }
              this.dataList = [...this.dataList,...content]
              this.uniHideLoading()
              Promise.resolve()
            })
            .catch(err => {
              if (this.query.keyword !== val){
                this.uniHideLoading()
                return
              }
              const { content } = err
              if (content.length === 0){
                this.end = true
                this.uniHideLoading()
                return
              }
              this.dataList = [...this.dataList,...content]
              this.uniHideLoading()
              Promise.resolve()
            })
      }

    },
    addCu(){
      this.bWidth = 0
      this.cuIndex = 1
      this.filePath = null
      this.form = Object.assign({},form)
      this.open()
    },
    updateCu(val){
      try{
        this.visitTime = JSON.parse(val.visitTime).map(item=>this.timelist[~~item - 1].name).join(',')
      }catch{
        this.visitTime =  ''
      }
 
      this.bWidth = 0
      this.cuIndex = 3
      this.filePath = null
      console.log(val, this.form.visitTime,'‘靠靠靠靠靠靠靠给',this.visitTime);
      this.form = val
      this.open()
      this.$nextTick(()=>{
        if(this.form.visitTime){
        const multiSelectList = JSON.parse(this.form.visitTime).map(item=>this.timelist[item-1])
        // this.$refs.visitTimeText.updateInputMultiSelectList(multiSelectList)
      }else{
        // this.$refs.visitTimeText.updateInputMultiSelectList([])
      }
      })
    },
    credit(val){
      this.creditData = {}
      this.$set(this.creditData,'customerId',val.id)
      this.$set(this.creditData,'customerCode',val.code)
      this.$set(this.creditData,'customerName',val.name)
      this.$set(this.creditData,'deliveryAddress',val.deliveryAddress)
      this.$set(this.creditData,'location',val.location)
      this.$set(this.creditData,'contactName',val.contactName)
      this.$set(this.creditData,'contactPhone',val.contactPhone)
      this.$set(this.creditData,'creditLimit',val.creditLimit)
      this.$set(this.creditData,'cardNo',val.cardNo)
      this.$set(this.creditData,'creditLevel',val.creditLevel)
      const creditLevelName = this.creditLevelList.find(item=>item.value === val.creditLevel)
      this.$set(this.creditData,'creditLevelName',creditLevelName.label)
      console.log(this.creditData)
      this.open(true)
    },
    creditSave(){
      uni.showLoading()
      if (this.creditData.imageUrl && this.creditData.stampImageUrl){
        this.creditSubmit()
      }else {
        this.saveImg(this.stampFilePath,this.creditData,'stampImageUrl')
        this.saveImg(this.filePath,this.creditData,'imageUrl')
      }
    },
    sleepTime(a,b,c){
      setTimeout(()=>{
        if (a&&b){
          console.log(c)
        }else {
          this.sleepTime()
        }
      },1000)
    },
    updateImg(val){
      this.bWidth = 1500
      this.filePath = null
      this.form = val
      this.open()
    },
    getCustomerList(){
      if (!this.end) {
        this.query.page += 1
        this.API_appletBasCustomer()
      }
    },
    save(){
      if (!this.form.id){
        this.form.customerAttr = 3
      }
      for(let key in this.rules){
        if (!this.form[key]){
          uni.showToast({title:`${this.rules[key]}为空`,icon: 'error'})
          return
        }
      }
      if (this.filePath){
        this.goImage(this.filePath,this.form.imageUrl)
      }else {
        this.submit()
      }
    },
    select(e){
      this.filePath = e.tempFilePaths[0]
    },
    stampSelect(e){
      this.stampFilePath = e.tempFilePaths[0]
    },
    open(type = false){
      this.isCredit = type
      // 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
      this.$refs.popup.open('bottom')
      this.mask = true
    },
    close(){
      // 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
      this.$refs.popup.close()
      this.mask = false
    },
    addCuIndex(){
      this.cuIndex += 1
      this.bWidth += 750
    },
    reduceCuIndex(){
      this.cuIndex -= 1
      this.bWidth -= 750
    },
    queryCustomer(val){
      this.init()
      this.query.keyword=val
      this.API_appletBasCustomer(val)
    },
    getimg(item){
      if (item.imageUrl){
        return JSON.parse(item.imageUrl)[0].path
      }else {
        return 'https://www.zjjqf.cn/file/static/undefined.png'
      }
    },
    // 操作--查看数据
    onDetail(item){
      if(this.form.id || this.appletExtraDict.appletIsAllowModifyCustomer !== '1'){
        return
      }
      uni.navigateTo({
        url: `/pages/saleplace/scustomerList`,
      })
    },
    // onDetail(item) {
    //   let obj = JSON.stringify(item)
    //   uni.navigateTo({
    //     url: `/pages/saleplacedetail/index?obj=${obj}&type=DETAIL`,
    //   })
    // },

    // 选中门店
    onSelectedPosi(item) {
      // this.dataList.forEach(cur => {
      //   this.$set(cur, 'isActive', false)
      // })
      // this.$set(item, 'isActive', true)
      const app = getApp()
      app.globalData.selectedPosition = item
      // 路由跳转到商品页面
      uni.navigateBack()
    },
    saveImg(filePath,object,name){
      uni.uploadFile({
        url: 'https://www.zjjqf.cn/api/common/uploadImage',
        filePath,
        name: 'file',
        header:{
          Authorization: getToken()
        },
        formData: {
          'user': 'test'
        },
        success: (res) => {
          const { id,path,realName } = JSON.parse(res.data).data
          object[name] = JSON.stringify([{ id,path,realName }])
          if (object['stampImageUrl'] && object['imageUrl']){
            this.creditSubmit()
          }
          filePath = null
          return true
        }
      });
      },
    async creditSubmit(){
      uni.hideLoading()
      appletBasCustomerCreditAddOrSave(this.creditData).then(res=>{
        if (res.status === 200){
          uni.showToast({title:res.msg,icon:'none'})
          this.creditData = {}
          this.filePath = null
          this.stampFilePath = null
          this.close()
        }else {
          uni.showToast({title:res.msg,icon:'none'})
        }
      }).catch(err=>{
        uni.showToast({title:err.msg,icon:'none'})
      })
    },
    goImage(filePath,imgPath){
      uni.uploadFile({
        url: 'https://www.zjjqf.cn/api/common/uploadImage',
        filePath,
        name: 'file',
        header:{
          Authorization: getToken()
        },
        formData: {
          'user': 'test'
        },
        success: (res) => {
          const { id,path,realName } = JSON.parse(res.data).data
          imgPath = JSON.stringify([{ id,path,realName }])
          this.form.imageUrl = imgPath
          this.submit()
          this.filePath = null
          return true
        }
      });
    },
    submit(){
      // uni.showLoading()
      appBasCustomerAddOrSave(this.form).then(res=>{
        if (res.status === 200){
          uni.showToast({
            title: res.msg,
            icon: 'success'
          })
          uni.hideLoading()
          this.close()
          this.form = form
          this.init()
          this.API_appletBasCustomer()
        }else {
          uni.showToast({
            title: res.msg,
            icon: 'error'
          })
          uni.hideLoading()
        }
      }).catch(err=>{
        uni.hideLoading()
        uni.showToast({
          title: err.msg,
          icon: 'error'
        })
      })
    },
    // 确认
    onConfirm() {
      let selectedPosition = this.dataList.find(d => d.isActive)

      if (!selectedPosition) {
        this.uniShowToast('请选择售点门店')
        // this.onCancel()
      } else {
        const app = getApp()
        app.globalData.selectedPosition = selectedPosition
        // 路由跳转到商品页面
        uni.navigateBack()
      }

      // 路由跳转到商品页面
    },
    // changetime(val){
    //   this.form.visitTime=JSON.stringify(val.map(item=>{return item.id}))
    // },
    // changeline(val){
    //   this.form.visitLineId=val.id
    //   this.form.visitLineName=val.name
    // },
    changeArea(val){
      this.form.customerAreaId=val.id
      this.form.customerAreaName=val.name
    },
    changetype(val){
      this.form.customerTypeId=val.id
      this.form.customerTypeName=val.name
    },
    onchange(val,type,showName){
      this.form[showName] = val.id
      this.form[type] = val.id
      const user = this.userList.find(item=>item.id === val.id)
      this.$set(this.form,'userPhone',user.phone )
    },
    changeCreditlevel(e){
      console.log(e)
    },
    // 取消
    onCancel() {
      const app = getApp()
      app.globalData.selectedPosition = null

      // 路由跳转到商品页面
      uni.navigateBack()
    },

    getCurrentLocation() {
      const th = this
      uni.getLocation({
        type: 'wgs84',
          isHighAccuracy:true,
        altitude:false,
        success: function (res) {
          // th.form.price = Number(th.form.price)
          console.log(`经纬度:${res.longitude},${res.latitude}`)
        }
      });
    },

    // 获取选择地址
    getaddress() {
      let that = this
      uni.chooseLocation({
        success: function(res) {
          that.form.address = res.address
          that.form.location = `${res.longitude},${res.latitude}`
        }
      });
    },

    // 获取选择地址
    getCreditaddress() {
      let that = this
      uni.chooseLocation({
        success: function(res) {
          that.$set(that.creditData,'deliveryAddress',res.address)
          that.$set(that.creditData,'location',`${res.longitude},${res.latitude}`)
        }
      });
    },
  },
}
</script>

<style scoped lang="scss">
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 15rpx 0;
  text-align: center;
  background-color: #ffffff;
}
.div_content {
  height: 1200rpx;
  overflow: scroll;
}

.list_item {
  padding: 20rpx 15rpx;
  display: flex;
  border-bottom: 1px solid #ddd;
  .place_info {
    flex: 1;
    padding-left: 20rpx;
    padding-top: 20rpx;
  }
  .op_wrap {
    width: 160rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .btn_op {
      padding: 0rpx 30rpx;
      font-size: 24rpx;
      margin: 6rpx 0;
    }
  }
}

// 点中的门店项
.isActive.list_item {
  background-color: $activeColor;
  color: #fff;
}

.customer{
  position: relative;
  z-index: 999;
  .title{
    font-size: 36rpx;
    height: 100rpx;
  }
}
.customerContent{
  overflow: hidden;
  height: 800rpx;
  white-space: nowrap;
  transition: margin 0.2s linear;
  .b1{
    padding-left: 30rpx;
    min-width: 750rpx;
    float: left;
  }
  .b1-1{
    overflow-y: auto;
    overflow-x: hidden;
  }
  .cuInputBox{
    border-bottom: rgba(203,203,203,0.2) 1px solid;
    height: 90rpx;
    .label{
      font-family: 微软雅黑;
      font-size: 30rpx;
      width: 200rpx;
      flex-shrink: 0;
    }
    .cuIpt{
      width: 100%;
    }
  }
}
.btnBox{
    padding: 0 30rpx;
  .cuBtn{
    background-color: red;
    flex: 1;
    line-height: 100rpx;
    border-radius: 100rpx;
    color: #ffffff;
  }

}
.fileBox{
  width: 100%;
  height: 100%;
  .text{
    width: 100%;
    font-size: 60rpx;
    padding: 20rpx;
  }

}
.red{
  color: red;
  font-size: 30rpx;
  height: 30rpx;
  width: 20rpx;
}
.ash{
  color: rgb(153,153,153);
font-size: 12px;
}
.locationImage{
  width: 30rpx;
  height: 30rpx;
}
.locationImage1{
  width: 40rpx;
  height: 40rpx;
}
.photoTitle{
  font-family: 微软雅黑;
  font-size: 30rpx;
  width: 200rpx;
  padding: 30rpx 0;
}
</style>
